package com.ash.other;

import com.ash.util.ConnectionUtil;
import com.ash.util.ConnectionsUtil;

import java.sql.*;
import java.util.Objects;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/8 14:05
 * @Author : Chen Chao
 * @File : connection.com.ash.other.Test06.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 获取自动生成的主键
 */
public class Test06 {
    public static void main(String[] args) {
        String name="张三";
        int age=19;
        test01(name+"01", age);
        test02(name+"02", age);
    }

    /**
     * 使用预普通语句获取自动生成的主键
     * @param name 用户名
     * @param age 年龄
     */
    private static void test02(String name,int age) {
        Connection connection = ConnectionUtil.getConnection();
        String sql="insert into student (name,age) values('"+name+"',"+age+")";
        Statement statement=null;
        ResultSet generatedKeys=null;
        try {
            statement = Objects.requireNonNull(connection).createStatement();
            /*执行是填入获取主键*/
            statement.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
            generatedKeys = statement.getGeneratedKeys();
            if(generatedKeys.next()){
                int anInt = generatedKeys.getInt(1);
                System.out.println(name+"生成的id是"+anInt);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,statement,generatedKeys);
        }

    }

    /**
     * 使用预编译语句获取自动生成的主键
     * @param name 用户名
     * @param age 年龄
     */
    private static void test01(String name,int age) {
        Connection connection = ConnectionsUtil.getConnection();
        String sql="insert into student (name,age) values(?,?)";
        PreparedStatement ps=null;
        ResultSet keys=null;
        try {
            /*创建时填入获取主键*/
            ps = Objects.requireNonNull(connection).
                    prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setObject(1,name);
            ps.setObject(2,age);
            ps.executeUpdate();
            keys = ps.getGeneratedKeys();
            if(keys.next()){
                int anInt = keys.getInt(1);
                System.out.println(name+"生成的id是"+anInt);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionsUtil.close(connection,ps,keys);
        }
    }
}
